<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="拼团状态" prop="actionStatus">
        <el-select v-model="queryParams.actionStatus">
          <el-option
            v-for="item in actionStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="拼团名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入拼团名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['monitor:group:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['monitor:group:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['monitor:group:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['monitor:group:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="goodsGroupId" />
      <el-table-column label="拼团图片" align="center" width="80">
        <template v-slot="scope">
          <el-image
            :src="scope.row.mainImgUrl"
            fit="fill"
            width="80%">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="拼团名称" align="center" prop="groupName" width="250"/>
      <el-table-column label="成团数量" align="center" prop="successNum" />
      <el-table-column label="活动状态" align="center" prop="actionStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_action_status" :value="getActualActionStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" key="goodsStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.goodsStatus"
            active-value="0"
            inactive-value="1"
            :disabled="isSwitchDisabled(scope.row.goodsStatus)"
            @change="handleStatusChange(scope.$index, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="开团时长" align="center" prop="time" />
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-if="isEditButtonVisible(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['monitor:group:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="handleCopy(scope.row)"
            v-hasPermi="['monitor:group:copy']"
          >复制</el-button>
          <el-button
            v-if="!isEditButtonVisible(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetails(scope.row)"
            v-hasPermi="['monitor:group:details']"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['monitor:group:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 选择商品列表 -->
    <el-dialog
      title="选择商品"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleClose">
      <el-form :model="goodsParams" ref="queryGoodsForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input
            v-model="goodsParams.goodsName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGoodsQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetGoodsQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="products" style="width: 100%">
        <el-table-column label="商品id" align="center" prop="goodsId" width="80"/>
        <el-table-column label="商品图片" align="center" width="80">
          <template slot-scope="scope">
            <img :src="scope.row.mainImgUrl" alt="商品图片" style="width: 100%; height: auto; max-height: 80px;">
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="goodsName" width="300"/>
        <el-table-column label="价格" align="center" prop="sellingPrice" width="70"/>
        <el-table-column label="库存" align="center" prop="stock" width="50"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="selectProduct(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="goodsParams.total>0"
        :total="goodsParams.total"
        :page.sync="goodsParams.pageNum"
        :limit.sync="goodsParams.pageSize"
        @pagination="chooseGoodsList"
      />
    </el-dialog>

    <!-- 添加或修改拼团商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="142px" size="small">
        <el-form-item label="选择商品:" prop="goodsId" class="label__add__font">
          <el-col :span="15" v-if="isAddGoods">
            <el-button @click="chooseGoodsList" size="mini">选择商品+</el-button>
          </el-col>
          <div v-if="selectedProduct">
            <!-- 创建一个只包含 selectedProduct 的数组 -->
            <el-table :data="[selectedProduct]" border style="width: 100%">
<!--              <el-table-column label="商品id" align="center" prop="goodsId" width="80"/>-->
              <el-table-column label="商品图片" align="center" width="80">
                <template slot-scope="scope">
                  <img :src="scope.row.mainImgUrl" alt="商品图片" style="width: 100%; height: auto; max-height: 80px;">
                </template>
              </el-table-column>
              <el-table-column label="商品名称" align="center" prop="goodsName" width="300"/>
              <el-table-column label="价格" align="center" prop="sellingPrice" width="90"/>
              <el-table-column label="库存" align="center" prop="stock" width="90"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                <template slot-scope="scope" v-if="isAddGoods">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="deleteProduct(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="拼团设置:" prop="setGroupData" class="label__add__font">
          <el-col :span="15" v-if="setGroupData.length < 3">
            <el-button @click="addSetGroup" size="mini">添加拼团阶梯</el-button>
          </el-col>
          <div v-if="setGroupData.length > 0">
            <el-table :data="setGroupData" border style="width: 100%">
              <el-table-column label="阶梯" align="center" width="80">
                <template slot-scope="scope">
                  <span>{{ `第${scope.$index + 1}阶梯` }}</span>
                </template>
              </el-table-column>
              <el-table-column label="阶梯人数" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    v-model.number="scope.row.groupPeople"
                    controls-position="right"
                    :min="2"
                    :max="300"
                  />
                </template>
              </el-table-column>
              <el-table-column label="拼团价格" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    v-model.number="scope.row.groupPrice"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    :min="0"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" @click="removeSetGroup(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="拼团名称:" prop="groupName" class="label__add__font">
          <el-input v-model="form.groupName" placeholder="请输入拼团名称" />
        </el-form-item>
        <el-form-item label="拼团简介:" prop="groupDesc" class="label__add__font">
          <el-input type="textarea" v-model="form.groupDesc" placeholder="请输入拼团简介"></el-input>
        </el-form-item>
        <el-form-item  label="拼团时间" class="label__add__font" prop="value1">
          <el-date-picker
            v-model="form.value1"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange">
          </el-date-picker>
          <div class="upload-tip">设置活动开启结束时间，用户可以在设置时间内发起参与拼团</div>
        </el-form-item>
        <el-form-item label="物流方式:" prop="logisticsMode" class="label__add__font">
          <el-checkbox-group v-model="form.logisticsMode">
            <el-checkbox v-for="item in logisticsOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="库存量:" prop="stock" class="label__add__font">
          <el-input-number
            v-model.number="form.stock"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="拼团时效(单位 小时):" prop="time" class="label__add__font">
          <el-input-number
            v-model.number="form.time"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">用户发起拼团后开始计时，需在设置时间内邀请到规定好友人数参团，超过时效时间，则系统判定拼团失败，自动发起退款</div>
        </el-form-item>
        <el-form-item label="限购规则:" prop="isRestrict" class="label__add__font">
          <el-radio-group v-model="form.isRestrict">
            <el-radio
              v-for="item in restrictOptions"
              :key="item.value"
              :label="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总购买数量限制:" prop="payCount" class="label__add__font" v-if="form.isRestrict === 0">
          <el-input-number
            v-model.number="form.payCount"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">该商品活动期间内，用户可购买的最大数量。例如设置为4，表示本次活动有效期内，每个用户最多可购买4件</div>
        </el-form-item>
        <el-form-item label="单次购买数量限制:" prop="oncePayCount" class="label__add__font" v-if="form.isRestrict === 0">
          <el-input-number
            v-model.number="form.oncePayCount"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">用户参与拼团时，一次购买最大数量限制。例如设置为2，表示每次参与拼团时，用户一次购买数量最大可选择2个</div>
        </el-form-item>

        <el-form-item label="单独设置:" prop="isCommission" class="label__add__font">
          <el-checkbox-group v-model="isCommission">
            <el-checkbox v-for="item in commissionOptions" :key="item.value" :label="item.value" @change="handleCommissionChange(item.value)">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div>
          <el-table v-if="this.form.isCommission === 1" border :data="tableData">
            <el-table-column label="平台方" align="center">
              <template slot-scope="scope">
                <!-- 注意这里不再使用 scope.form，而是直接使用 form 对象 -->
                <el-input-number
                  style="width: 80%"
                  v-model.number="form.platformCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>

            </el-table-column>
            <el-table-column label="发起方" align="center">
              <template slot-scope="scope">
                <el-input-number
                  style="width: 80%"
                  v-model.number="form.initiatorCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="分享者" align="center">
              <template slot-scope="scope">
                <el-input-number
                  style="width: 80%"
                  v-model.number="form.sharerCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="合作方" align="center">
              <template slot-scope="scope">
                <el-input-number
                  style="width: 80%"
                  v-model.number="form.partnerCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>




        <el-form-item label="模拟成团:" class="label__add__font" prop="fictiStatus">
          <el-switch
            v-model="form.fictiStatus"
            active-text="开启"
            inactive-text="关闭"
          ></el-switch>
        </el-form-item>
        <div class="upload-tip" style="margin-top: -15px;width: 680px;margin-left: 142px">开启模拟成团后，满足条件的团，系统将会拟“匿名买家"凑满该团，仅需对真实拼团买家发货，建议合理开启，以提高成团率。</div>
        <div v-if="form.fictiStatus && form.fictiStatus !== '0'" style="margin-left: 142px;margin-top: 10px;">
          <el-radio-group v-model="form.fictiNum">
            <el-radio label="all">所有未拼成的团</el-radio>
            <el-radio label="custom">
              参团人数≥
              <el-input-number
                v-model.number="form.groupNum"
                controls-position="right"
                :min="1"
                :max="300"
              />
              的团
            </el-radio>
          </el-radio-group>
        </div>
        <el-form-item label="凑团:" class="label__add__font" prop="gatherStatus">
          <el-switch v-model="form.gatherStatus" active-text="开启" inactive-text="关闭"></el-switch>
          <div class="upload-tip">开启凑团后，活动商品详情可屏示未成团的团列表，买家可以任选一个团参团，提升成团率。</div>
        </el-form-item>
<!--        <el-form-item label="活动状态:" class="label__add__font" prop="actionStatus">
          <el-switch v-model="form.actionStatus" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拼团商品详情 -->
    <el-dialog :title="titleDetail" :visible.sync="openDetail" width="850px" append-to-body>
      <el-form ref="form" :model="form"  label-width="142px" size="small">
        <el-form-item label="选择商品:" prop="goodsId" class="label__add__font">
          <div v-if="selectedProduct">
            <!-- 创建一个只包含 selectedProduct 的数组 -->
            <el-table :data="[selectedProduct]" border style="width: 100%">
              <!--              <el-table-column label="商品id" align="center" prop="goodsId" width="80"/>-->
              <el-table-column label="商品图片" align="center" width="80">
                <template slot-scope="scope">
                  <img :src="scope.row.mainImgUrl" alt="商品图片" style="width: 100%; height: auto; max-height: 80px;">
                </template>
              </el-table-column>
              <el-table-column label="商品名称" align="center" prop="goodsName" width="300"/>
              <el-table-column label="价格" align="center" prop="sellingPrice"/>
              <el-table-column label="库存" align="center" prop="stock"/>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="拼团设置:" prop="setGroupData" class="label__add__font">
          <div v-if="setGroupData.length > 0">
            <el-table :data="setGroupData" border style="width: 100%">
              <el-table-column label="阶梯" align="center" width="80">
                <template slot-scope="scope">
                  <span>{{ `第${scope.$index + 1}阶梯` }}</span>
                </template>
              </el-table-column>
              <el-table-column label="阶梯人数" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    :disabled="disabledDetail"
                    v-model.number="scope.row.groupPeople"
                    controls-position="right"
                    :min="2"
                    :max="300"
                  />
                </template>
              </el-table-column>
              <el-table-column label="拼团价格" align="center">
                <template slot-scope="scope">
                  <el-input-number
                    :disabled="disabledDetail"
                    v-model.number="scope.row.groupPrice"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    :min="0"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item label="拼团名称:" prop="groupName" class="label__add__font">
          <el-input v-model="form.groupName" placeholder="请输入拼团名称" :disabled="disabledDetail"/>
        </el-form-item>
        <el-form-item label="拼团简介:" prop="groupDesc" class="label__add__font">
          <el-input type="textarea" v-model="form.groupDesc" placeholder="请输入拼团简介" :disabled="disabledDetail"></el-input>
        </el-form-item>
        <el-form-item  label="拼团时间" class="label__add__font" prop="value1">
          <el-date-picker
            :disabled="disabledDetail"
            v-model="form.value1"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange">
          </el-date-picker>
          <div class="upload-tip">设置活动开启结束时间，用户可以在设置时间内发起参与拼团</div>
        </el-form-item>
        <el-form-item label="物流方式:" prop="logisticsMode" class="label__add__font">
          <el-checkbox-group v-model="form.logisticsMode" :disabled="disabledDetail">
            <el-checkbox v-for="item in logisticsOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="库存量:" prop="stock" class="label__add__font">
          <el-input-number
            :disabled="disabledDetail"
            v-model.number="form.stock"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="拼团时效(单位 小时):" prop="time" class="label__add__font">
          <el-input-number
            :disabled="disabledDetail"
            v-model.number="form.time"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">用户发起拼团后开始计时，需在设置时间内邀请到规定好友人数参团，超过时效时间，则系统判定拼团失败，自动发起退款</div>
        </el-form-item>
        <el-form-item label="限购规则:" prop="isRestrict" class="label__add__font">
          <el-radio-group v-model="form.isRestrict">
            <el-radio
              :disabled="disabledDetail"
              v-for="item in restrictOptions"
              :key="item.value"
              :label="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总购买数量限制:" prop="payCount" class="label__add__font" v-if="form.isRestrict === 0">
          <el-input-number
            :disabled="disabledDetail"
            v-model.number="form.payCount"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">该商品活动期间内，用户可购买的最大数量。例如设置为4，表示本次活动有效期内，每个用户最多可购买4件</div>
        </el-form-item>
        <el-form-item label="单次购买数量限制:" prop="oncePayCount" class="label__add__font" v-if="form.isRestrict === 0">
          <el-input-number
            :disabled="disabledDetail"
            v-model.number="form.oncePayCount"
            controls-position="right"
            :min="1"
          />
          <div class="upload-tip">用户参与拼团时，一次购买最大数量限制。例如设置为2，表示每次参与拼团时，用户一次购买数量最大可选择2个</div>
        </el-form-item>

        <el-form-item label="单独设置:" prop="isCommission" class="label__add__font">
          <el-checkbox-group v-model="isCommission" :disabled="disabledDetail">
            <el-checkbox v-for="item in commissionOptions" :key="item.value" :label="item.value" @change="handleCommissionChange(item.value)">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div>
          <el-table v-if="this.form.isCommission === 1" border :data="tableData">
            <el-table-column label="平台方" align="center">
              <template slot-scope="scope">
                <!-- 注意这里不再使用 scope.form，而是直接使用 form 对象 -->
                <el-input-number
                  :disabled="disabledDetail"
                  style="width: 80%"
                  v-model.number="form.platformCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>

            </el-table-column>
            <el-table-column label="发起方" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :disabled="disabledDetail"
                  style="width: 80%"
                  v-model.number="form.initiatorCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="分享者" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :disabled="disabledDetail"
                  style="width: 80%"
                  v-model.number="form.sharerCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="合作方" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :disabled="disabledDetail"
                  style="width: 80%"
                  v-model.number="form.partnerCommission"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item label="模拟成团:" class="label__add__font" prop="fictiStatus">
          <el-switch
            :disabled="disabledDetail"
            v-model="form.fictiStatus"
            active-text="开启"
            inactive-text="关闭"
          ></el-switch>
        </el-form-item>
        <div class="upload-tip" style="margin-top: -15px;width: 680px;margin-left: 142px">开启模拟成团后，满足条件的团，系统将会拟“匿名买家"凑满该团，仅需对真实拼团买家发货，建议合理开启，以提高成团率。</div>
        <div v-if="form.fictiStatus && form.fictiStatus !== '0'" style="margin-left: 142px;margin-top: 10px;">
          <el-radio-group v-model="form.fictiNum" :disabled="disabledDetail">
            <el-radio label="all">所有未拼成的团</el-radio>
            <el-radio label="custom">
              参团人数≥
              <el-input-number
                v-model.number="form.groupNum"
                controls-position="right"
                :min="1"
                :max="300"
              />
              的团
            </el-radio>
          </el-radio-group>
        </div>
        <el-form-item label="凑团:" class="label__add__font" prop="gatherStatus">
          <el-switch v-model="form.gatherStatus" active-text="开启" inactive-text="关闭" :disabled="disabledDetail"></el-switch>
          <div class="upload-tip">开启凑团后，活动商品详情可屏示未成团的团列表，买家可以任选一个团参团，提升成团率。</div>
        </el-form-item>
        <el-form-item label="活动状态:" class="label__add__font" prop="actionStatus">
          <el-switch v-model="form.actionStatus" active-text="开启" inactive-text="关闭" :disabled="disabledDetail"></el-switch>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listGroup, getGroup, delGroup, addGroup, updateGroup, changeGoodsGroupStatus } from '@/api/marketing/group'
import { changeGoodsStatus, listGoods } from '@/api/goods/goods'

export default {
  name: "Group",
  dicts: ['sys_action_status','sys_goods_status'],
  data() {
    return {
      disabledDetail:true,
      // 用于存储每个商品的额外状态信息
      extraStatus: {},
      isAddGoods: true,
      tableData:[{}],
      switchText: '关闭', // 初始状态
      isCommission:[],
      isAsterisk: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拼团商品信息表格数据
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      titleDetail: "",
      openDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        actionStatus: null,
      },
      goodsParams:{
        pageNum: 1,
        pageSize: 10,
        total:0,
        goodsName: null,
        goodsField:"goods_id,main_img_url,goods_name,selling_price,stock,status"
      },
      logisticsOptions: [
        { value: 1, label: '快递' },
        { value: 2, label: '到店核销' }
      ],
      actionStatusOptions: [
        { value: "0", label: '开启' },
        { value: "1", label: '关闭' }
      ],
      restrictOptions: [
        { value: 0, label: '限购' },
        { value: 1, label: '不限购' }
      ],
      commissionOptions: [
        { value: 1, label: '佣金设置(数字即返佣金额)' },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: '请选择商品', trigger: 'blur' },
        ],
        setGroup: [
          { required: true, message: '请设置拼团信息', trigger: 'blur' }
        ],
        groupName: [
          { required: true, message: '请输入拼团名称', trigger: 'blur' }
        ],
        groupDesc: [
          { required: true, message: '请输入拼团简介', trigger: 'blur' }
        ],
        value1: [
          { type: 'array', required: true, message: '请选择拼团时间', trigger: 'change' }
        ],
        time: [
          { required: true, message: '请输入拼团时效', trigger: 'blur' }
        ],
        payCount: [
          { required: true, message: '请输入总购买数量限制', trigger: 'blur' }
        ],
        oncePayCount: [
          { required: true, message: '请输入单次购买数量限制', trigger: 'blur' }
        ],
      },
      //选择商品参数
      dialogVisible: false,
      searchQuery: '',
      products: [],
      selectedProduct: null,
      filteredProducts: [],
      setGroupData:[],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 观察 form.fictiStatus 的变化
    'form.fictiStatus'(newVal) {
      if (newVal) {
        // 当开关被打开时（即 newVal 为 true）
        if(this.form.fictiNum === 0){
          this.form.fictiNum = 'all';
        }
      } else {
        // 如果需要在关闭时重置 fictiNum，可以在这里添加逻辑
        // 例如：this.form.fictiNum = '';
      }
    }
  },
  methods: {
    handleCommissionChange(changedValue) {
      // 检查是否选中了特定的复选框（例如值为 '1' 的复选框）
      // this.showTable = this.selectedCommissions.includes('1');
      const isSelected = this.isCommission.includes(changedValue);
      if (isSelected) {
        console.log('Selected:', changedValue);
        this.form.isCommission = changedValue;
        // 处理选中逻辑
      } else {
        console.log('Deselected:', changedValue);
        this.form.isCommission = 0;
        // 处理取消选中逻辑
      }
    },
    /** 查询拼团商品信息列表 */
    getList() {
      this.loading = true;
      listGroup(this.queryParams).then(response => {
        this.total = response.data.total??0;
        if(this.total>0){
          this.groupList = response.data.data.map(item => ({
            ...item, // 复制当前项的所有属性
            mainImgUrl: process.env.VUE_APP_BASE_API + item.mainImgUrl, // 拼接新的图片 URL
          }));
        }else{
          this.groupList = response.data.data;
        }
        this.total = response.data.total;
        this.loading = false;
      });
    },

    addSetGroup() {
      const goodsId = this.form.goodsId;
      if (goodsId) {
        // 创建一个新的拼团数据对象，并设置默认值
        const newGroup = {
          groupPeople: 1,  // 默认阶梯人数为1
          groupPrice: 0,   // 默认拼团价格为0
        };
        // 将新的拼团数据对象添加到数组中
        this.setGroupData.push(newGroup);
      } else {
        this.$modal.msgError("请先选择商品再设置拼团信息");
      }
    },
    removeSetGroup(index) {
      // 从数组中移除指定索引的对象
      this.setGroupData.splice(index, 1);
    },
    handleDateChange(value) {
      if (value && value.length === 2) {
        const startTime = value[0];  // 开始时间
        const endTime = value[1];    // 结束时间
        this.form.startTime = startTime;
        this.form.endTime = endTime;
      }
    },
    chooseGoodsList(){
      listGoods(this.goodsParams).then(response => {
        this.products = response.data.data.map(item => ({
          ...item, // 复制当前项的所有属性
          mainImgUrl: process.env.VUE_APP_BASE_API + item.mainImgUrl, // 拼接新的图片 URL
        }));
        this.goodsParams.total = response.data.total;
        this.dialogVisible = true;
      });
    },

    handleClose() {
      this.dialogVisible = false;
      this.searchQuery = '';
      this.goodsParams.goodsName = null;
    },
    selectProduct(product) {
      this.selectedProduct = product;
      this.dialogVisible = false;
      this.goodsParams.goodsName = null;
      this.form.goodsId = product.goodsId;
      // this.form.goodsStatus = product.status;
      this.form.groupName = product.goodsName;
    },
    deleteProduct(product){
      this.selectedProduct = null;
      this.setGroupData = [];
      this.goodsParams.goodsName = null;
      this.form.goodsId = null;
      // this.form.goodsStatus = '0';
      this.form.groupName = null;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsGroupId: null,
        goodsId: null,
        groupName: null,
        groupDesc: null,
        startTime: null,
        endTime: null,
        time: 0,
        logisticsMode: [2],
        buyingCountNum: 0,
        buyingNum: 0,
        payCount: 0,
        oncePayCount: 0,
        goodsStatus: '0',
        fictiStatus: false,
        successNum: 0,
        price: 0,
        gatherStatus:false,
        actionStatus: false,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        setGroupDataList:[],
        value1: [],  // 初始化为空数组，用于存储开始和结束时间
        fictiNum: 'all', // 默认选择所有未拼成的团
        groupNum: null, // 用户输入的参团人数
        categorySelected:[],
        isRestrict: 0,
        stock: 0,
        isCommission: 0,
        platformCommission: 0,
        initiatorCommission: 0,
        sharerCommission: 0,
        partnerCommission: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleGoodsQuery() {
      this.goodsParams.pageNum = 1;
      this.chooseGoodsList();
    },
    /** 重置按钮操作 */
    resetGoodsQuery() {
      this.resetForm("queryGoodsForm");
      this.handleGoodsQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsGroupId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.selectedProduct = null;
      this.isAddGoods = true;
      this.setGroupData = [];
      this.isCommission = [];
      this.reset();
      this.open = true;
      this.title = "添加拼团商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isAddGoods = false;
      const goodsGroupId = row.goodsGroupId || this.ids
      getGroup(goodsGroupId).then(response => {
        this.form = response.data;
        this.isCommission = this.form.isCommissionArr;
        this.setGroupData = this.form.setGroupDataList;
        this.selectedProduct = this.form.goodsData;
        this.form.stock = this.form.goodsData.stock;
        this.selectedProduct.mainImgUrl = process.env.VUE_APP_BASE_API + this.form.goodsData.mainImgUrl; // 拼接新的图片 URL
        this.open = true;
        this.title = "修改拼团商品信息";
      });
    },
    /** 复制按钮操作 */
    handleCopy(row) {
      this.reset();
      this.isAddGoods = true;
      const goodsGroupId = row.goodsGroupId || this.ids
      getGroup(goodsGroupId).then(response => {
        this.form = response.data;
        this.isCommission = this.form.isCommissionArr;
        this.setGroupData = this.form.setGroupDataList;
        this.selectedProduct = this.form.goodsData;
        this.form.stock = this.form.goodsData.stock;
        this.selectedProduct.mainImgUrl = process.env.VUE_APP_BASE_API + this.form.goodsData.mainImgUrl; // 拼接新的图片 URL
        this.form.goodsGroupId = null;
        this.open = true;
        this.title = "修改拼团商品信息";
      });
    },
    handleDetails(row){
      const goodsGroupId = row.goodsGroupId || this.ids
      getGroup(goodsGroupId).then(response => {
        this.form = response.data;
        this.isCommission = this.form.isCommissionArr;
        this.setGroupData = this.form.setGroupDataList;
        this.selectedProduct = this.form.goodsData;
        this.form.stock = this.form.goodsData.stock;
        this.selectedProduct.mainImgUrl = process.env.VUE_APP_BASE_API + this.form.goodsData.mainImgUrl; // 拼接新的图片 URL
        this.openDetail = true;
        this.titleDetail = "拼团商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.setGroupDataList = this.setGroupData;
      this.$refs["form"].validate(valid => {
        console.log(this.form);
        if (valid) {
          if (this.form.goodsGroupId != null) {
            updateGroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsGroupIds = row.goodsGroupId || this.ids;
      this.$modal.confirm('是否确认删除拼团商品信息编号为"' + goodsGroupIds + '"的数据项？').then(function() {
        return delGroup(goodsGroupIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/SGroup/exportGoodsGroup', {
        ...this.queryParams
      }, `group_${new Date().getTime()}.xlsx`)
    },
    // 拼团商品状态修改
    handleStatusChange(index, row) {
      let text = row.goodsStatus === "0" ? "上架" : "下架";
      this.$modal.confirm('确认要"' + text + '""' + row.groupName + '"拼团商品吗？').then(function() {
        return changeGoodsGroupStatus(row.goodsGroupId, row.goodsStatus, row.goodsId);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        // 更新额外状态信息
        const newActionStatus = row.goodsStatus === "0" ? "0" : "1"; // 根据 goodsStatus 确定 actionStatus
        this.$set(this.extraStatus, row.goodsGroupId, {
          actionStatus: newActionStatus,
          isEditButtonVisible: row.goodsStatus === "0", // 上架时显示修改按钮，下架时隐藏
        });
      }).catch(function() {
        row.goodsStatus = row.goodsStatus === "0" ? "1" : "0";
      });
    },
    getActualActionStatus(row) {
      // 根据额外状态信息返回实际的活动状态
      return this.extraStatus[row.goodsGroupId]?.actionStatus || row.actionStatus;
    },
    isEditButtonVisible(row) {
      // 根据额外状态信息判断修改按钮是否可见
      return this.extraStatus[row.goodsGroupId]?.isEditButtonVisible || (row.goodsStatus === "0" && row.actionStatus === "2");
    },
    isSwitchDisabled(goodsStatus) {
      // 当商品状态为下架（goodsStatus === 1）时，禁用开关
      if(goodsStatus === '1'){
        return true;
      }else {
        return false;
      }
    },
  }
};
</script>
<style>
.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.product-item img {
  margin-right: 10px;
}
.label__add__font label {
  font-size: 13px;
  font-weight: normal;
}
.el-textarea__inner {
  margin-top: 0px;
  margin-bottom: 0px;
  height: 100px;
  width: 400px;
}
.upload-tip {
  color: #999; /* 灰色文字 */
  font-size: 12px; /* 字体大小 */
  text-align: left; /* 文本居中 */
}
</style>
